﻿Imports agsXMPP
Imports System.Runtime.InteropServices

Public Class chatwindow
    Public Property name As Jid
    Dim res As String
    Dim countText = 1
    Public Sub recMesg(ByVal message As agsXMPP.protocol.client.Message)
        '  If StackPanel1.Dispatcher.Thread.Equals(System.Threading.Thread.CurrentThread) Then

        '  Else
        '     StackPanel1.Dispatcher.BeginInvoke(New (AddressOf recMesg), New String() {message, fromP})
        ' Return
        ' End If
        Dim title As String
        Try
            title = CType(Application.Current.Windows.Item(0), MainWindow).contactNicks(CType(Application.Current.Windows.Item(0), MainWindow).contactsJIDS.IndexOf(name.Bare))
        Catch ex As Exception
            title = message.From.User
        End Try
        If message.From.Resource IsNot Nothing And message.From.Resource <> "" Then
            res = message.From.Resource
        End If
        If message.Type = protocol.client.MessageType.headline Then
            Me.Title = title + message.Body
        End If
        If message.Chatstate = protocol.extensions.chatstates.Chatstate.composing Then
            Me.Title = title + " is typing..."
        ElseIf message.Chatstate = protocol.extensions.chatstates.Chatstate.paused Then
            Me.Title = title + " was typing"
        ElseIf message.Chatstate = protocol.extensions.chatstates.Chatstate.gone Then
            Me.Title = title + " has left"
        ElseIf message.Chatstate = protocol.extensions.chatstates.Chatstate.active Then
            Me.Title = title
        ElseIf message.Chatstate = protocol.extensions.chatstates.Chatstate.inactive Then
            Me.Title = title
        ElseIf message.Chatstate = protocol.extensions.chatstates.Chatstate.None Then
            Me.Title = title
        End If

        If message.Body = "" Then
            Exit Sub
        End If

        AddMessage(message.Body, title)


    End Sub
    Private Sub AddMessage(ByVal message As String, ByVal sender As String)
        Dim content As New FlowDocument()
        Try
            content = chatBoxContent.Document
        Catch ex As Exception
        End Try
        Dim m As Paragraph
        Try
            m = content.Blocks.FirstBlock
        Catch ex As Exception
            m = New Paragraph()
        End Try

        Dim r As New Run()
        Dim n As New LineBreak()
        Dim mess As String = sender + " says, " + message
        If sender = "You" Then
            mess = sender + " say, " + message
        Else
            If Me.IsActive = False Then
                Dim a As Application = Application.Current
                If a.newMessages.ContainsKey(name.Bare) Then
                    a.newMessages(name.Bare) += 1
                Else
                    a.newMessages.Add(name.Bare, 1)
                End If
                Dim numNewMess As Integer = 0
                For Each u In a.newMessages.Values
                    numNewMess += u
                Next
                Dim iconWidth As Integer = 20
                Dim iconHeight As Integer = 20


                Dim bmp As New RenderTargetBitmap(iconWidth, iconHeight, 96, 96, PixelFormats.[Default])

                Dim root As New ContentControl()

                root.ContentTemplate = DirectCast(Resources("OverlayIcon"), DataTemplate)
                root.Content = numNewMess

                root.Arrange(New Rect(0, 0, iconWidth, iconHeight))

                bmp.Render(root)

                TaskbarItemInfo.Overlay = DirectCast(bmp, ImageSource)
                'TaskbarItemInfo.ThumbButtonInfos.Item(0).ImageSource = DirectCast(bmp, ImageSource)
                'Me.TaskbarItemInfo.Overlay = CType(Resources("OverlayImage"), ImageSource)

            End If
        End If
        r.Text = mess
        m.Inlines.Add(r)
        m.Inlines.Add(n)
        content.Blocks.Add(m)
        chatBoxContent.Document = content
        chatBoxContent.ScrollToEnd()
        scrollerBar.ScrollToBottom()
        If Me.IsFocused Then
            chatBox.Focus()
        End If

    End Sub

    Private Sub chatwindow_Activated(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Activated
        UpdateTaskBar()
    End Sub
    Private Sub UpdateTaskBar()
        Debug.WriteLine("Updating taskbar...")
        Dim a As Application = Application.Current
        If a.newMessages.ContainsKey(name.Bare) Then
            a.newMessages(name.Bare) = 0
        Else
            a.newMessages.Add(name.Bare, 0)
        End If
        Dim numNewMess As Integer = 0
        For Each u In a.newMessages.Values
            numNewMess += u
        Next
        If numNewMess = 0 Then
            Debug.WriteLine("Removing overlay...")
            TaskbarItemInfo.Overlay = Nothing

        Else
            Debug.WriteLine("There are still " + numNewMess.ToString() + " messages left!!!!!!!!!!!!")
            Dim iconWidth As Integer = 20
            Dim iconHeight As Integer = 20


            Dim bmp As New RenderTargetBitmap(iconWidth, iconHeight, 96, 96, PixelFormats.[Default])

            Dim root As New ContentControl()

            root.ContentTemplate = DirectCast(Resources("OverlayIcon"), DataTemplate)
            root.Content = numNewMess

            root.Arrange(New Rect(0, 0, iconWidth, iconHeight))

            bmp.Render(root)

            TaskbarItemInfo.Overlay = DirectCast(bmp, ImageSource)

        End If

    End Sub
    Private Sub chatwindow_Closed(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Closed
        Dim m As Application = Application.Current()
        m.windowsOpen.Remove(name.Bare)

    End Sub

    Private Sub chatwindow_ContentRendered(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.ContentRendered
        Me.Topmost = False
    End Sub

    Private Sub chatwindow_GotFocus(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles Me.GotFocus
        UpdateTaskBar()
    End Sub

    Private Sub chatwindow_Loaded(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles Me.Loaded
        Dim m As Application = Application.Current()
        m.windowsOpen.Add(name.Bare.ToLower())
        Me.Title = CType(Application.Current.Windows.Item(0), MainWindow).contactNicks(CType(Application.Current.Windows.Item(0), MainWindow).contactsJIDS.IndexOf(name.Bare))
        '  Me.BringIntoView()
    End Sub


    Private Sub chatBox_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Input.KeyEventArgs) Handles chatBox.KeyDown
        If e.Key = Key.Enter Then
            Dim m As New agsXMPP.protocol.client.Message()
            m.Type = protocol.client.MessageType.chat
            If res IsNot Nothing And res <> "" Then
                name.Resource = res
            End If
            m.To = name
            m.Body = chatBox.Text

            Dim mw As MainWindow = Application.Current.Windows.Item(0)
            mw.ags.Send(m)
            AddMessage(chatBox.Text, "You")
            chatBox.Text = ""
        Else
            Dim m As New protocol.client.Message()
            m.Chatstate = protocol.extensions.chatstates.Chatstate.composing
            If res IsNot Nothing And res <> "" Then
                name.Resource = res
            End If
            m.To = name
            Dim mw As MainWindow = Application.Current.Windows.Item(0)
            mw.ags.Send(m)

        End If
    End Sub
  
End Class
